﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using EzDesk.DevHelper.DebugLibrary;
using System.Web.Security;
using System.Reflection;
using EzDesk.DevHelper.DebugLibrary.Model;
using EzDesk.DevHelper.DebugLibrary.Helper;
using System.Data.Odbc;
using System.Xml.Linq;

namespace EzDesk.DevHelper.DebugLibrary
{

    public class EzDeskInitial : IEzDeskInitial
    {
        protected EzDeskDataContext db = new EzDeskDataContext();
        List<IEzDeskInitial> initials = new List<IEzDeskInitial>();

        protected void InitialFeedsTemplate(Guid appId, string xmlFileName)
        {
            XElement rootElement = XElement.Load(xmlFileName);
            var feeds = rootElement.Elements();
            foreach (var feed in feeds)
            {
                Guid id = Guid.Empty;
                if (feed.Element("id") != null)
                {
                    id = new Guid(feed.Element("id").Value);
                }
                string templateName = null;
                if (feed.Element("name") != null)
                {
                    templateName = feed.Element("name").Value;
                }
                string title = null;
                if (feed.Element("title") != null)
                {
                    title = feed.Element("title").Value;
                }
                string body = null;
                if (feed.Element("body") != null)
                {
                    body = feed.Element("body").Value;
                }
                int type = 0;
                if (feed.Element("type") != null)
                {
                    type = Int32.Parse(feed.Element("type").Value);
                }

                db.ez_FeedTemplates.InsertOnSubmit(
                    new ez_FeedTemplate()
                    {
                        AppId = appId,
                        TemplateName = templateName,
                        TempleId = id,
                        Title = title,
                        Body = body,
                        Type = type,
                    }
                    );
            }
            db.SubmitChanges();
        }


        protected void CreateBasicInfo(Guid appId, string name, string title, string description, Dictionary<string, string> domains)
        {
            Debug.WriteLine(string.Format("开始添加 {0} App...", name));
            db.ez_Apps.InsertOnSubmit(
                new ez_App()
                {
                    AppId = appId,
                    Name = name,
                    Description = description,
                    Title = title,
                }
                );
            foreach (var item in domains)
            {
                db.ez_AppDomains.InsertOnSubmit(
                    new ez_AppDomain()
                    {
                        AppId = appId,
                        UserAgentType = item.Key,
                        Domain = item.Value,
                    }
                    );
            }
            db.SubmitChanges();
            Debug.WriteLine(string.Format("{0} App添加成功", name));
        }

        #region IEzDeskInitial Members

        void IEzDeskInitial.Initialize()
        {
            //清空数据库
            CleanupDatabase();

            //删除Membership中所有注册信息
            ImportBasicDataFromDb();

            //建立分组
            CreateBasicGroups();
            
            foreach (var init in initials)
            {
                init.Initialize();
            }

            Debug.WriteLine("完成!");
        }


        #endregion

        #region IEzDeskInitial Members


        public void AddInitializeModule(IEzDeskInitial initial)
        {
            initials.Add(initial);
        }

        #endregion

        private void CreateBasicGroups()
        {
            db.ez_Groups.InsertOnSubmit(
                new ez_Group()
                    {
                        GroupId = Guid.NewGuid(),
                        MemberString = "everyone",
                        Description = "所有人",
                        Type = 0,
                    });
            db.SubmitChanges();
            Debug.WriteLine("所有人 分组建立完成");


            //建立各部门分组
            var depts = from d in db.ez_Depts
                        select d;
            foreach (var dept in depts)
            {
                List<string> usersInDept = (from u in dept.ez_UserProfiles
                                            select u.UserId.ToString()).ToList();

                Guid newGroupId = Guid.NewGuid();
                db.ez_Groups.InsertOnSubmit(
                    new ez_Group()
                        {
                            GroupId = newGroupId,
                            MemberString = GroupMemeberStrHelper.GetGroupMemberStrFromList(usersInDept, null),
                            Description = dept.DeptName,
                            Type = 1,
                        });

                dept.GroupId = newGroupId;
                db.SubmitChanges();
            }
            
            Debug.WriteLine("各部门分组建立完成");
        }

        private void ImportBasicDataFromDb()
        {
            CleanupMembershipData();

            Dictionary<string, Guid> positionDict = new Dictionary<string, Guid>();
            Dictionary<string, Guid> deptDict = new Dictionary<string, Guid>();

            string connStr = @"Driver={Microsoft Access Driver (*.mdb)};Dbq=EzDesk.mdb";
            using (OdbcConnection conn = new OdbcConnection(connStr))
            {
                conn.Open();

                // 导入部门
                string sqlStr = "SELECT * FROM dept ";
                OdbcCommand cmd = new OdbcCommand(sqlStr, conn);
                OdbcDataReader dr = cmd.ExecuteReader();
                while(dr.Read())
                {
                    Guid newDeptId = Guid.NewGuid();
                    db.ez_Depts.InsertOnSubmit(
                        new ez_Dept()
                        {
                            DeptId = newDeptId,
                            DeptName = dr["dept"] as string,
                        }
                        );
                    deptDict.Add(dr["dept"] as string, newDeptId);
                }
                db.SubmitChanges();
                Debug.WriteLine("部门 导入完毕！");
                

                // 导入职位
                sqlStr = "SELECT * FROM userlevel ";
                cmd = new OdbcCommand(sqlStr, conn);
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Guid newPosId = Guid.NewGuid();
                    db.ez_Positions.InsertOnSubmit(
                        new ez_Position()
                        {
                            PosId = newPosId,
                            Priority =  (int)dr["pri"],
                            Description = dr["userlevel"] as string,
                        }
                        );
                    positionDict.Add(dr["userlevel"] as string, newPosId);
                }
                db.SubmitChanges();
                Debug.WriteLine("职位 导入完毕！");
                
                //导入人员
                sqlStr = "SELECT * FROM userinf ";
                cmd = new OdbcCommand(sqlStr, conn);
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string username = dr["username"] as string;
                    string name = dr["name"] as string;
                    Membership.CreateUser(username, "123456", "xx@@@.com");

                    //固定3个User的UserId，供测试用：
                    //"877c3323-17a7-42d1-9d75-402ffc894e63", "Karin"
                    //"19f1c421-280f-4935-9980-e469175461c2", "龚伟"
                    //"0c9d7c0c-04a5-4ae2-97a1-d7bbc38f5c66", "杨裕欣"
                    //"ce36c495-38cc-4b7e-875e-364ff8e087b5", "卢春叶"
                    Guid newUserId = Guid.NewGuid();
                    switch (name)
                    {
                        case "Karin":
                            newUserId = new Guid("877c3323-17a7-42d1-9d75-402ffc894e63");
                            break;
                        case "龚伟":
                            newUserId = new Guid("19f1c421-280f-4935-9980-e469175461c2");
                            break;
                        case "杨裕欣":
                            newUserId = new Guid("0c9d7c0c-04a5-4ae2-97a1-d7bbc38f5c66");
                            break;
                        case "卢春叶":
                            newUserId = new Guid("ce36c495-38cc-4b7e-875e-364ff8e087b5");
                            break;
                    }
                    db.ez_UserProfiles.InsertOnSubmit(
                        new ez_UserProfile()
                        {
                            UserId = newUserId,
                            DeptId = deptDict[dr["userdept"] as string],
                            PosId = positionDict[dr["userlevel"] as string],
                            UserName = username,
                            Name = name,
                        }
                        );
                }
                db.SubmitChanges();
                Debug.WriteLine("人员 导入完毕！");
            }
        }


        private static void CleanupMembershipData()
        {
            Debug.WriteLine("清除MemberShip数据库");
            MembershipUserCollection users = Membership.GetAllUsers();
            foreach (MembershipUser user in users)
            {
                Membership.DeleteUser(user.UserName);
            }
            Debug.WriteLine("MemberShip用户全部清除!");
        }

        private void CleanupDatabase()
        { 
            // 
            db.ez_Recipient_Feeds.DeleteAllOnSubmit(db.ez_Recipient_Feeds);
            db.SubmitChanges();

            //清空Feed
            db.ez_Feeds.DeleteAllOnSubmit(db.ez_Feeds);
            db.SubmitChanges();
            Debug.WriteLine("提醒全部清空!");


            //清空Feed模板
            db.ez_FeedTemplates.DeleteAllOnSubmit(db.ez_FeedTemplates);
            db.SubmitChanges();
            Debug.WriteLine("Feeds模板全部清除!");

            //清空AppDomain列表
            db.ez_AppDomains.DeleteAllOnSubmit(db.ez_AppDomains);
            db.SubmitChanges();
            Debug.WriteLine("AppDomains全部清除!");

            //清空App列表
            db.ez_Apps.DeleteAllOnSubmit(db.ez_Apps);
            db.SubmitChanges();
            Debug.WriteLine("App全部清除!");

            //清空人员
            db.ez_UserProfiles.DeleteAllOnSubmit(db.ez_UserProfiles);
            db.SubmitChanges();
            Debug.WriteLine("人员信息全部清空！");


            //清空部门
            db.ez_Depts.DeleteAllOnSubmit(db.ez_Depts);
            db.SubmitChanges();
            Debug.WriteLine("部门信息已经全部清除!");

            //清空分组
            db.ez_Groups.DeleteAllOnSubmit(db.ez_Groups);
            db.SubmitChanges();
            Debug.WriteLine("分组数据全部清除!");
            
            //清空职位
            db.ez_Positions.DeleteAllOnSubmit(db.ez_Positions);
            db.SubmitChanges();
            Debug.WriteLine("职位信息已经全部清除!");
        }


    }



}
